# 6.2.2
alien_0 = {
    'color': 'green',
    'points': 5
}

print(alien_0)

# 可以利用   列表名['key'] = value  这种形式添加 或 修改 列表元素
alien_0["x_position"] = 0
alien_0['y_position'] = 25
print(alien_0)

# 6.2.4
# 修改字典中键值对中的值
alien_0 = {
    'x_position': 0,
    'y_position': 25,
    'speed': 'medium'
}
print(f'Original position: {alien_0["x_position"]}, {alien_0["y_position"]}')

if alien_0['speed'] == 'slow':
    x_increment = 1
elif alien_0['speed'] == 'medium':
    x_increment = 2
else:
    x_increment = 3

# 注意：在利用f''时，里面的所有表达式尽量用双引号“”
print(f'New position: {alien_0["x_position"] + x_increment}, {alien_0["y_position"] }')

# 6.2.5
# 利用del删除键值对
alien_0 = {
    'color': 'green',
    'points': 5
}

del alien_0['points']
print(alien_0)

# 在利用  列表名['key'] = value  这种形式访问 或 修改列表元素时
# 如果选择的 key 在字典中不存在，则会抛出异常
# 此时可以用  get()方法  来访问字典中的值
# get()方法中有两个参数，
# 第一个参数应该是一个关键字，
# 第二个参数是，在 所给关键字不存在时，应该返回的字符串
# 注意：第二个参数可以没有，
# 当没有指定get()方法中的第二个参数，
# 且作为该方法的第一个参数并不在列表中时，该方法会返回一个None

alien_0 = {
    'color': 'green',
    'speed': 'medium'
}
pointValue = alien_0.get('points', 'No point value assigned')
print(pointValue)

# 6.2后的动手试一试
# 练习6.1
personInfo = {
    'firstName': 'shi',
    'lastName': 'maoqing',
    'age': 24,
    'city': 'anshun'
}
print(personInfo['firstName'])
print(personInfo['lastName'])
print(personInfo['age'])
print(personInfo['city'])

# 6.3.1
# 要想遍历字典中的键值对，可利用items()方法
# 这个方法会返回一个键值对列表，
# 在进行for循环时，列表作为一个可迭代对象，
# 每次利用items()方法会按照顺序依次给入
# 键值对列表，列表第一个元素是关键字，第二个元素是值
user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi'
}
for key, value in user_0.items():
    print(f'\nKey: {key}')
    print(f'Value: {value}')

favoriteLanguage = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'rust',
    'phil': 'python'
}
for name, language in favoriteLanguage.items():
    print(f"{name.title()}'s favorite language is {language.title()}.")

# 6.3.2
# 可以利用keys方法只提取字典中的关键字，以此实现字典的遍历
favoriteLanguage = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'rust',
    'phil': 'python'
}
for name in favoriteLanguage.keys():
    print(name.title())

# 实际上，字典作为一个可迭代对象，在for循环中如果直接把字典名称作为被迭代对象
# 会默认遍历的是关键字
# 此时如下的程序也会得到与上一段程序相同的运行结果
favoriteLanguage = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'rust',
    'phil': 'python'
}
for name in favoriteLanguage:
    print(name.title())

# 从上面的for循环可以看出，keys()方法返回的是一个列表对象
# 那么就可以用in 和 not in 判断一个元素是否在这个列表中存在了
favoriteLanguage = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'rust',
    'phil': 'python'
}
# 下面这两句话的结果相同
if 'erin' not in favoriteLanguage:
    print('Erin, please take our poll')
if 'erin' not in favoriteLanguage.keys():
    print('Erin, please take our poll')

# 6.3.4-1
# values()方法能够将所有字典中的值排在一个列表中
# 但是values()方法不会考虑值是否有重复
favoriteLanguage = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'rust',
    'phil': 'python'
}
print('The following languages have been mentioned: ')
for language in favoriteLanguage.values():
    print(language.title())

# 6.3.4-2
# 上一段程序中得到的列表可能有重复项，为了剔除这些重复项，可使用集合set
favoriteLanguage = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'rust',
    'phil': 'python'
}
print('The following languages have been mentioned: ')
for language in set(favoriteLanguage.values()):
    print(language.title())

# 注意：这里的集合的定义是和字典类似的
#      用一个花括号{}括起来就能形成一个集合，比如：
languages = {'python', 'rust', 'python', 'c'}
print(languages)

# 6.3后面的动手试一试
# 练习6.4
programmableTerms = {
    'list': 'combination of a series of elements that can be modified',
    'tuple': 'combination of a series of elements that can not be modified',
    'method': 'operations that Python can perform on the data',
    'f_string': 'the format that replaces the variables in the brace by its value',
    'set': 'a series of elements that do not include the same elements',
    'dictionary': 'a map of one or many key-value pair',
    'slice of list': 'divide a list through three '
                     'parameters, which include step size,'
                     ' original position and last position',
    'function of range()': 'the function will return a list of a series of numbers',
    'method of sort()': 'a method that can be used to sort a list',
    'function of sorted()': 'the function will return a sorted list'
}
for term, meaning in programmableTerms.items():
    print(f'{term}: {meaning}\n')

# 练习6.5
rivers_and_country = {
    'nile': 'egypt',
    'yangZe river': 'china',
    'yellow river': 'china'
}
for river, country in rivers_and_country.items():
    print(f'The {river.title()} runs through {country.title()}\n')

# 6.4.1
# 在列表中存储字典
aliens = []
for alien_number in range(30):
    new_alien = {
        'color': 'green',
        'points': 5,
        'speed': 'slow'
    }
    aliens.append(new_alien)

for alien in aliens[:5]:
    print(alien)

print(f'Total number of aliens: {len(aliens)}')

# 6.4.2-1
# 在字典中存储列表
pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese']
}

print(f'You ordered a {pizza["crust"]}-crust pizza with following toppings: ')
for topping in pizza['toppings']:
    print(f'\t{topping}')

# 6.4.2-2
# 访问字典中某个列表的某一个元素
favoriteLanguages = {
    'jen': ['python', 'rust'],
    'sarah': ['c'],
    'edward': ['rust', 'go'],
    'phil': ['python', 'haskell']
}
for name, languages in favoriteLanguages.items():
    print(f"{name.title()}'s favorite languages are:")
    for language in languages:
        print(f'\t{language.title()}')

# 6.4.3
# 在字典中存储字典
users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton'
    },
    'mcuie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris'
    }
}

for username, userInfo in users.items():
    print(f'\nUsername: {username}')
    fullname = f'{userInfo["first"]} {userInfo["last"]}'
    location = f'{userInfo["location"]}'
    print(f'\tFull name: {fullname.title()}')
    print(f'\tLocation: {location.title()}')

# 6.4后的动手试一试
# 练习6.7
# 注意：对字典这个对象使用value()，key()这两种方法时，
#      返回的结果不是一个列表，
#      返回的数据类型是dict_values 和 dict_keys
#      这两个数据类型并不是列表，
#      所以不可以使用切片，也不可以只打印一部分 关键字  或  取值
me = {
    'firstName': 'shi',
    'lastName': 'maoqing',
    'age': 24,
    'city': 'anshun'
}
father = {
    'firstName': 'shi',
    'lastName': 'xuedong',
    'age': 55,
    'city': 'anshun'
}
mother = {
    'firstName': 'yang',
    'lastName': 'li',
    'age': 50,
    'city': 'anshun'
}
people = [me, father, mother]
for person in people:
    # print(type(person.values()))

    print(f"fullName is {person['firstName'].title()}{person['lastName']}")
    print(f"age is {person['age']}")
    print(f"city is {person['city'].title()}")
    print('\n')

# 练习6.9
favoritePlaces = {
    'shimaoqing': ['tianjin', 'beijing', 'shanghai'],
    'shixuedong': ['huangping', 'anshun'],
    'yangli': ['wengan', 'anshun']
}
for name, places in favoritePlaces.items():
    print(f"{name}'s favorite places are: ")
    for place in places:
        print(f'\t{place}')

# 练习6.11
cities = {
    'paris': {
        'country': 'french',
        'population': '1 million',
        'fact': ' is located in Europe'
    },
    'beijing': {
        'country': 'china',
        'population': '2 million',
        'fact': ' is located in Asian'
    },
    'london': {
        'country': 'britain',
        'population': '1.5 million',
        'fact': ' is located in Europe'
    }
}
for city, information in cities.items():
    print('\n')
    print(f"Information about {city.title()} includes:")
    info = cities[city]
    print(f"{city.title()} belongs to country which is called {info['country'].title()}.")
    print(f"The {city.title()}'s population is {info['population']}.")
    print(f"The fact about {city.title()} is that {info['country'].title()}{info['fact']}.")
